package cn.yuhao.party.intui.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.intui.domain.InDomain;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;

public class InDao {
private QueryRunner qr = new TxQueryRunner();

	
	public PageBean<InDomain> findAll(int pc) {
		int ps = PageConstants.BOOK_PAGE_SIZE;// 每页记录数
		String sql = "select * from uic limit ?,?";
		try {
			String sql1 = "select count(*) from uic";
			Number number = (Number) qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();// 得到了总记录数
			List<InDomain> listInDomain = qr.query(sql,
					new BeanListHandler<InDomain>(InDomain.class), (pc - 1) * ps,
					ps);
			PageBean<InDomain> pb = new PageBean<InDomain>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listInDomain);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);

			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public InDomain findById(String Gtheme) {
		String sql = "select * from uic where theme=?";

		try {
			InDomain InDomain = (InDomain) qr.query(sql, new BeanHandler<InDomain>(
					InDomain.class), Gtheme);
			return InDomain;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void addInDomain(InDomain InDomain) {
		String sql = "insert into uic values(?,?,?,?,?)";
		Object[] params = { InDomain.getTheme(),InDomain.getContex(),InDomain.getPicture(),InDomain.getLink(),InDomain.getNumber()};
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String theme) {
		String sql = "delete from uic where theme=?";
		try {
			qr.update(sql, theme);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void editInDomain(InDomain InDomain) {
		String sql = "update uic set contex=?,picture=?,link=?,number=?  where theme=?";
		Object[] params = {  InDomain.getContex(),InDomain.getPicture(),InDomain.getLink(),InDomain.getNumber(),InDomain.getTheme()};
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
